from ad8232 import AD8232 #导入AD8232库
from machine import Pin, SPI #导入通信以及引脚相关的库
import st7789 #导入屏幕驱动库
import utime

heartRate = 0
heartRateStr = "0"
heartSensorValue = 0
height_old = 0
height_new = 0
STHEIGHT = 240
STWIDTH = 240
x = 1
y = 1
cnt = 0

heartSensor = AD8232(analogPin = 5, LO1Pin=2, LO2Pin=14) #构造心电传感器对象

spi = SPI(0, baudrate=40000000, polarity=1, phase=0, bits=8, endia=0, sck=Pin(6), mosi=Pin(8)) #构造spi对象
display = st7789.ST7789(spi, 240, 240, reset=Pin(11,func=Pin.GPIO, dir=Pin.OUT), dc=Pin(7,func=Pin.GPIO, dir=Pin.OUT)) #构造屏幕控制对象
display.init() #屏幕初始化

backgroud_clr = st7789.color565(255, 255, 255) #设置背景颜色为白色
line_clr = st7789.color565(0, 0, 0) #心电图显示用颜色
str_clr = st7789.color565(0,0,255) #心率显示用颜色
grid_clr = st7789.color565(242, 167, 167)

def draw_grid():
    grid_x = 0
    for i in range(12):
        display.line(grid_x, 0, grid_x, 239, grid_clr)
        display.line(0, grid_x, 239, grid_x, grid_clr)
        grid_x += 20

if __name__ == "__main__":
    display.fill(backgroud_clr)
    draw_grid()
    while True:
        if  heartSensor.value(LO = 1) == 1 or heartSensor.value(LO = 2) == 1: #判断电极片是否脱落
            print("!")
            heartSensorValue = 1100
            line_clr = st7789.color565(255, 0, 0) #电极片脱落后曲线颜色变为红色，心率数字颜色变为红色作为脱落提示
            str_clr = st7789.color565(255, 0, 0)
        else:
            heartSensorValue = heartSensor.read()   #读取心电传感器数据
            line_clr = st7789.color565(0, 0, 0)
            str_clr = st7789.color565(0,0,255)
        
        # 将心电数据转化为坐标，两点连线输出到屏幕
        y = int(heartSensorValue / 1200 * 240) - 100   
        height_new = 240 - y
        display.line(x-1, height_old, x, height_new, line_clr)

        if height_old - height_new >= 12: #寻找心电图R波(变化极快的波形)，并计算心率
            if cnt > 40:
                heartRate = 60 / (cnt * 0.01)
                cnt = 0
                if(heartRate<100):
                    heartRateStr = "0" + str(int(heartRate))
                else:
                    heartRateStr = str(int(heartRate))
                display.draw_string(170, 12, heartRateStr,size=4,color = str_clr) 
                print(heartRate)

        if x >= 240:
            x = 1
            display.fill(st7789.color565(255, 255, 255))
            draw_grid()
            display.draw_string(170, 12, heartRateStr,size=4,color = str_clr)
        else:
            x += 1

        height_old = height_new
        cnt += 1
        utime.sleep(0.01)
